//
//  JobCertificationViewController.m
//  MyProject
//
//  Created by 石小强 on 2018/4/14.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "JobCertificationViewController.h"
#import "FindPeopleFlowLayout.h"
#import "JobCerticationViewCell.h"
#import "JobCerticationLayout.h"
#import <QiniuSDK.h>
#import "AppDelegate.h"
#import "NSUDManager.h"
#import "CompanyInfoCertificateVC.h"
#import "PictureViewController.h"

@interface JobCertificationViewController ()<JobCerticationLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) JobCerticationViewCell *selectCell;

@property (nonatomic, strong) JobCerticationViewCell *work_card_cell;
@property (nonatomic, strong) JobCerticationViewCell *company_email_cell;
@property (nonatomic, strong) JobCerticationViewCell *labor_contract_cell;
@property (nonatomic, strong) JobCerticationViewCell *incumbency_certification_cell;

@end

@implementation JobCertificationViewController {
    // 工牌： INCUMBENT_AUTHENTICATION_WORK_CARD
    // 企业邮箱： INCUMBENT_AUTHENTICATION_COMPANY_EMAIL
    // 劳动合同： INCUMBENT_AUTHENTICATION_LABOR_CONTRACT
    // 在职证明： INCUMBENT_AUTHENTICATION_INCUMBENCY_CERTIFICATION
    NSString *_work_card_key;
    NSString *_company_email_key;
    NSString *_labor_contract_key;
    NSString *_incumbency_certification_key;
    
    UIImage *_work_card_image;
    UIImage *_company_email_image;
    UIImage *_labor_contract_image;
    UIImage *_incumbency_certification_image;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"上传资料";
    
    [self setupMainView];
    // 获取七牛上传凭证
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"qiniu"] == nil) {
//        [self getQiuNiuUpToken];
//    }
}


- (void)setupMainView {
    self.view.backgroundColor = kStyleColor;
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.navigationController.view.backgroundColor = [UIColor clearColor];
    
    self.headerIconIV.layer.cornerRadius = 19.5;
    self.headerIconIV.layer.masksToBounds = YES;
    
    CGFloat itemW = kScreenWidth - 20;
    CGFloat itemH = (kScreenWidth - 34) * 410 / 343;
    
    CGFloat viewH = kScreenHeight - 193 - NAV_STATUS_H;
    
    JobCerticationLayout *layout = [[JobCerticationLayout alloc] init];
    layout.itemSize = CGSizeMake(itemW, itemH);
    layout.scale = 0.9;
    layout.delegate = self;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewH) collectionViewLayout:layout];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.backgroundColor = kStyleColor;
    collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView = collectionView;
    [self.centerView addSubview:collectionView];
    
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([JobCerticationViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"JobCerticationViewCell"];
    
    UserModel *user = [NSUDManager currentUser];
    
    [self.headerIconIV sd_setImageWithURL:ImageURLWithKey(user.headImg) placeholderImage:PlaceholderImage];
    self.headerNameL.text = self.name;
    self.headerCompanyAndPositionL.text = [NSString stringWithFormat:@"%@ | %@", self.companyName, self.params[@"positionName"]];
}


#pragma mark - JobCerticationLayoutDelegate

- (void)scrolledToTheCurrentItemAtIndex:(NSInteger)itemIndex {
    self.pageNumber = itemIndex;
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JobCerticationViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JobCerticationViewCell" forIndexPath:indexPath];
    cell.backgroundColor = kStyleColor;
    cell.work_card_key = _work_card_key;
    cell.company_email_key = _work_card_key;
    cell.labor_contract_key = _labor_contract_key;
    cell.incumbency_certification_key = _incumbency_certification_key;
    
    cell.work_card_image = _work_card_image;
    cell.company_email_image = _company_email_image;
    cell.labor_contract_image = _labor_contract_image;
    cell.incumbency_certification_image = _incumbency_certification_image;
    
    cell.pageIndex = indexPath.row;
    WS(weakSelf)
    cell.imageBtnBlock = ^(NSInteger index, JobCerticationViewCell *cell) {
        
        if (index == 0) {
            if (_work_card_key && _work_card_key.length > 0) {
                PictureViewController *picture = [[PictureViewController alloc] init];
                picture.img = _work_card_image;
                [self presentViewController:picture animated:NO completion:nil];
            } else {
                weakSelf.selectCell = cell;
                UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:nil, nil];
                [sheet showInView:self.view];
                [weakSelf.view endEditing:YES];
            }
        } else if (index == 1) {
            if (_company_email_key && _company_email_key.length > 0) {
                PictureViewController *picture = [[PictureViewController alloc] init];
                picture.img = _company_email_image;
                [self presentViewController:picture animated:NO completion:nil];
            } else {
                weakSelf.selectCell = cell;
                UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:nil, nil];
                [sheet showInView:self.view];
                [weakSelf.view endEditing:YES];
            }
        } else if (index == 2) {
            if (_labor_contract_key && _labor_contract_key.length > 0) {
                PictureViewController *picture = [[PictureViewController alloc] init];
                picture.img = _labor_contract_image;
                [self presentViewController:picture animated:NO completion:nil];
            } else {
                weakSelf.selectCell = cell;
                UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:nil, nil];
                [sheet showInView:self.view];
                [weakSelf.view endEditing:YES];
            }
        } else {
            if (_incumbency_certification_key && _incumbency_certification_key.length > 0) {
                PictureViewController *picture = [[PictureViewController alloc] init];
                picture.img = _incumbency_certification_image;
                [self presentViewController:picture animated:NO completion:nil];
            } else {
                weakSelf.selectCell = cell;
                UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:nil, nil];
                [sheet showInView:self.view];
                [weakSelf.view endEditing:YES];
            }
        }
        
        
    };
    cell.reselectBtnBlock = ^(NSInteger index, JobCerticationViewCell *cell) {
        weakSelf.selectCell = cell;
        UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"请选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍摄" otherButtonTitles:nil, nil];
        [sheet showInView:self.view];
        [weakSelf.view endEditing:YES];
    };
    cell.deleteBtnBlock = ^(NSInteger index, JobCerticationViewCell *cell) {
        weakSelf.selectCell = cell;
        if (index == 0) {
            _work_card_key = @"";
            _work_card_image = nil;
        } else if (index == 1) {
            _company_email_key = @"";
            _company_email_image = nil;
        } else if (index == 2) {
            _labor_contract_key = @"";
            _labor_contract_image = nil;
        } else {
            _incumbency_certification_key = @"";
            _incumbency_certification_image = nil;
        }
//        cell.certerViewImageB.hidden = NO;
        cell.centerViewImageView.hidden = YES;
        cell.centerViewImageView.image = nil;
        cell.centerViewDeleteBtn.hidden = YES;
        cell.reselectBtn.hidden = YES;
        
        if ((!_work_card_key || [_work_card_key isEqualToString:@""]) && (!_company_email_key || [_company_email_key isEqualToString:@""]) && (!_labor_contract_key || [_labor_contract_key isEqualToString:@""]) && (!_incumbency_certification_key || [_incumbency_certification_key isEqualToString:@""])) {
            [weakSelf.submitBtn setTitle:@"拍照上传" forState:UIControlStateNormal];
        }
    };
    return cell;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍摄
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.view.tag = actionSheet.tag;
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
        
    }else if (buttonIndex == 1) {
        //从相册选择
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.view.tag = actionSheet.tag;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)aImage editingInfo:(NSDictionary *)editingInfo
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 获得编辑过的图片
    // 把图片转成NSData类型的数据来保存文件(存入到沙盒中)
    // 判断图片是不是png格式的文件
    NSData *imageData = UIImageJPEGRepresentation(aImage, 1.0);
    
    if (UIImagePNGRepresentation(aImage)) {
        // 返回为png图像。
    }else if (imageData){
        // 返回为JPEG图像
    }else{
        [[CommonUtils sharedCommonUtils]showAlert:@"请上传 jpeg或是png格式" delegate:nil];
        return;
    }
    
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    
    [YJMSendRequest postDataWithParameters:@{} url:@"common/getQiuNiuUpToken" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
//        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            NSString *token = result[@"data"][@"upToken"];
            //华北
            QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
                builder.zone = [QNFixedZone zone1];
            }];
            QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config];
            [upManager putData:imageData key:nil token:token complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                
                [weakSelf hideProgress:self.view animated:YES];
//                weakSelf.selectCell.certerViewImageB.hidden = YES;
                
                weakSelf.selectCell.centerViewImageView.hidden = NO;
                weakSelf.selectCell.centerViewImageView.image = aImage;
                weakSelf.selectCell.reselectBtn.hidden = NO;
                weakSelf.selectCell.centerViewDeleteBtn.hidden = NO;
                
                if (weakSelf.pageNumber == 0) {
                    _work_card_key = resp[@"key"];
                    _work_card_image = aImage;
                } else if (weakSelf.pageNumber == 1) {
                    _company_email_key = resp[@"key"];
                    _company_email_image = aImage;
                } else if (weakSelf.pageNumber == 2) {
                    _labor_contract_key = resp[@"key"];
                    _labor_contract_image = aImage;
                } else {
                    _incumbency_certification_key = resp[@"key"];
                    _incumbency_certification_image = aImage;
                }
                
                [weakSelf.submitBtn setTitle:@"提交审核" forState:UIControlStateNormal];
                
            } option:nil];
            
        }else{
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

#pragma mark - 获取七牛云上传凭证
- (void)getQiuNiuUpToken {
    [SendRequest getQiuNiuUpTokenWithResult:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            SaintiLog(@"获取七牛云上传凭证成功 = %@", [result objectForKey:@"data"]);
            NSString *qiniu = [[result objectForKey:@"data"] objectForKey:@"upToken"];
            [[NSUserDefaults standardUserDefaults] setValue:qiniu forKey:@"qiniu"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

#pragma mark - 按钮点击事件

- (IBAction)headerEditBtnClick:(id)sender {
    CompanyInfoCertificateVC *vc = [[CompanyInfoCertificateVC alloc] init];
    vc.editPage = 1;
    vc.params = self.params;
    vc.companyName = self.companyName;
    vc.jobName = self.jobName;
    vc.regionName = self.jobName;
    vc.minTimeStr = self.minTime;
    vc.maxTimeStr = self.maxTime;
    vc.editBlock = ^(NSMutableDictionary *params, NSString *companyName, NSString *jobName, NSString *regionName, NSString *minTime, NSString *maxTime) {
        self.params = params;
        self.companyName = companyName;
        self.jobName = jobName;
        self.regionName = regionName;
        self.minTime = minTime;
        self.maxTime = maxTime;
        
        self.headerCompanyAndPositionL.text = [NSString stringWithFormat:@"%@ | %@", self.companyName, params[@"positionName"]];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)submitBtnClick:(id)sender {
    /**
     NSString *_work_card_key;
     NSString *_company_email_key;
     NSString *_labor_contract_key;
     NSString *_incumbency_certification_key;
     */
    if ((!_work_card_key || _work_card_key.length == 0) && (!_company_email_key || _company_email_key.length == 0) && (!_labor_contract_key || _labor_contract_key.length == 0) && (!_incumbency_certification_key || _incumbency_certification_key.length == 0)) {
        [CommonUtils showToast:@"请上传资料"];
        return;
    }
    
    NSMutableArray *imgs = [NSMutableArray array];
    if (_work_card_key && _work_card_key.length > 0) {
        NSMutableDictionary *imgDict = [NSMutableDictionary dictionary];
        imgDict[@"imgKey"] = _work_card_key;
        imgDict[@"type"] = @"INCUMBENT_AUTHENTICATION_WORK_CARD";
#warning imgId-不知道怎么传
//        imgDict[@"imgId"] = @"";
        [imgs addObject:imgDict];
    }
    if (_company_email_key && _company_email_key.length > 0) {
        NSMutableDictionary *imgDict = [NSMutableDictionary dictionary];
        imgDict[@"imgKey"] = _company_email_key;
        imgDict[@"type"] = @"INCUMBENT_AUTHENTICATION_COMPANY_EMAIL";
//        imgDict[@"imgId"] = @"";
        [imgs addObject:imgDict];
    }
    if (_labor_contract_key && _labor_contract_key.length > 0) {
        NSMutableDictionary *imgDict = [NSMutableDictionary dictionary];
        imgDict[@"imgKey"] = _labor_contract_key;
        imgDict[@"type"] = @"INCUMBENT_AUTHENTICATION_LABOR_CONTRACT";
//        imgDict[@"imgId"] = @"";
        [imgs addObject:imgDict];
    }
    if (_incumbency_certification_key && _incumbency_certification_key.length > 0) {
        NSMutableDictionary *imgDict = [NSMutableDictionary dictionary];
        imgDict[@"imgKey"] = _incumbency_certification_key;
        imgDict[@"type"] = @"INCUMBENT_AUTHENTICATION_INCUMBENCY_CERTIFICATION";
//        imgDict[@"imgId"] = @"";
        [imgs addObject:imgDict];
    }
    
    NSMutableDictionary *paramsResult = self.params;
    paramsResult[@"imgs"] = imgs;
    
    WS(weakSelf)
    [self showProgressWithView:self.view animated:YES];
    [SendRequest submitIncumbentAuthenticationInfoWithParam:paramsResult result:^(NSDictionary *result, NSError *error) {
        [weakSelf hideProgress:self.view animated:YES];
        result = [CommonUtils decryptDicWithResult:result];
        if([result[@"result"] integerValue] == 1) {
            [YJMSendRequest postDataWithParameters:@{@"authenticationId":result[@"data"]} url:@"incumbent/submitAudit" result:^(NSDictionary *result, NSError *error) {
                result = [CommonUtils decryptDicWithResult:result];
                [self hideProgress:self.view animated:YES];
                if([result[@"result"] integerValue] == 1)
                {
                    // 认证成功
                    if (self.index == 1) {
                        [((AppDelegate *)[UIApplication sharedApplication].delegate) gotoHome];
                        
                    } else {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                    
                }else{
                    [CommonUtils showToast:[result objectForKey:@"msg"]];
                }
                
            }];
            
            
           
            
        } else {
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
    }];
}

@end
